package com.banmao.algorithm.No101To200.No110;

public class Solution1 {

    public boolean isBalanced(TreeNode root) {
        int height = getHeight(root);
        return height != -1;
    }

    public int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }

        TreeNode left = root.left;
        int leftHeight = getHeight(left);
        if(leftHeight == -1) {
            return -1;
        }

        TreeNode right = root.right;
        int rightHeight = getHeight(right);
        if(rightHeight == -1) {
            return -1;
        }

        return Math.abs(leftHeight - rightHeight) > 1 ? -1 : Math.max(leftHeight, rightHeight) + 1;

    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
